package com.service.setting.impl;



import com.comm.R;
import com.comm.vo.JsonResult;
import com.entity.AdministrativeOffice;
import com.entity.Registered;
import com.entity.Employee;
import com.github.pagehelper.PageHelper;
import com.entity.Menu;
import com.mapper.setting.MenMapper;
import com.mapper.setting.SysEmployeeMapper;
import com.service.setting.SysEmployeeService;
import com.utils.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;


@Service
public class SysEmployeeServiceImpl implements SysEmployeeService {

    @Autowired
    private SysEmployeeMapper sysEmployeeMapper;
    @Autowired
    private MenMapper menMapper;

    @Override
    public R login(String userName, String password, HttpServletResponse response) {

        R resultData=R.defaulted();
        try{

            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(userName,password);
            subject.login(usernamePasswordToken);
            resultData.setCode(200).setMsg("登录成功！");
            String currentToken = JwtUtils.createJwt(UUID.randomUUID().toString(), JwtUtils.JWT_SECERT, userName, JwtUtils.TTMILLIS);
            String refreshToken=JwtUtils.createJwt(UUID.randomUUID().toString(),JwtUtils.JWT_SECERT,userName,JwtUtils.TTMILLIS*2);

            response.addHeader("current_authorization",currentToken);
            response.addHeader("refresh_authorization",refreshToken);
            response.setHeader("Access-Control-Expose-Headers","current_authorization,refresh_authorization");


        }catch (UnknownAccountException e) {

        } catch (IncorrectCredentialsException e){
            resultData.setMsg("用户密码错误");
            System.out.println("用户密码错误");
        } catch (UnauthorizedException e){
            resultData.setMsg("角色错误");

            System.out.println("角色错误");
        } catch (LockedAccountException e){
            resultData.setMsg("账号被锁");

            System.out.println("账号被锁");
        } catch (AuthenticationException e){
            resultData.setMsg("认证错误");
            System.out.println("认证错误");
        }


        return resultData;

    }

    @Override
    public R getEmpByUserName(String userName) {
        R r=R.ok();
        Employee empByName = sysEmployeeMapper.findEmpByName(userName);
        if (!ObjectUtils.isEmpty(empByName)){
            r.setData(empByName);
        }else {
            r.setMsg("找不到数据").setCode(501);
        }
       return r;

    }


    /**
     *根据姓名查询用户信息
     */
    @Override
    public R findEmpByName(String emp_name) {

        R r = new R();
        try {
            List<Employee> empList = sysEmployeeMapper.findEmpByEmpName(emp_name);
            r.setCode(200);
            r.setMsg("查询成功");
            System.out.println(empList);
            r.setData(empList);
        } catch (Exception e) {
            e.printStackTrace();
            r.setCode(500);
            r.setMsg("系统开小差了，请联系管理员！");
        }

        return r;
    }


    /**
     * 根据员工Id禁用员工信息
     * @param id
     * @return
     */
    @Override
    public R stopEmpById(Integer id) {
        R r = new R();

        try {
            int row = sysEmployeeMapper.stopEmpById(id);

            if(row>0){
                r.setCode(200);
                r.setMsg("禁用成功");
            }else{
                r.setCode(500);
                r.setMsg("输入有误哦");
            }
        } catch (Exception e) {
            e.printStackTrace();
            r.setCode(500);
            r.setMsg("系统出现故障了哦");
        }
        return r;
    }

    /**
     * 根据员工id启用员工
     * @param id
     * @return
     */

    @Override
    public R startEmpById(Integer id) {
        R r = new R();

        try {
            int row = sysEmployeeMapper.startEmpById(id);

            if(row>0){
                r.setCode(200);
                r.setMsg("启动成功");
            }else{
                r.setCode(500);
                r.setMsg("输入有误哦");
            }
        } catch (Exception e) {
            e.printStackTrace();
            r.setCode(500);
            r.setMsg("系统出现故障了哦");
        }
        return r;
    }

    //已禁用人数按钮
    @Override
    public JsonResult findEmpStopNum() {
        JsonResult jsonResult = new JsonResult();

        try {
            Integer sum = sysEmployeeMapper.countStopSum();

            System.out.println(sum);
            if(sum>0){
                jsonResult.setCount(sum);

                List<Employee> empStopNum = sysEmployeeMapper.findEmpStopNum();
                //System.out.println(empStopNum);

                jsonResult.setCode(200);
                jsonResult.setMsg("查询成功");
                jsonResult.setData(empStopNum);
            }else{
                jsonResult.setCode(500);
                jsonResult.setMsg("没有数据哦");
            }
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.setCode(500);
            jsonResult.setMsg("系统出现故障了哦");
        }

        return jsonResult;
    }


    //分页查询员工信息
    @Override
    public JsonResult findEmpList(Integer currentPage, Integer pageSize) {

        JsonResult jsonResult = new JsonResult();
        try {
        com.github.pagehelper.Page<Registered> page = PageHelper.startPage(currentPage,pageSize);

        List<Employee> empList = sysEmployeeMapper.findEmpList();

        Integer count = sysEmployeeMapper.countEmp();
                jsonResult.setCode(200);
                jsonResult.setMsg("查询成功");
                jsonResult.setCount(count);
                jsonResult.setData(empList);
        } catch (NumberFormatException e) {
            e.printStackTrace();
            jsonResult.setCode(500);
            jsonResult.setMsg("系统出现了故障");
        }
        return jsonResult;
    }



    //添加员工
    @Override
    public R addEmp(Employee employee) {
        R r = new R();

        try {

            Integer row = sysEmployeeMapper.addEmp(employee);

            System.out.println("================="+row);

            if(row>0){
                r .setCode(200);
                r .setMsg("添加成功");
            }else{
                r .setCode(500);
                r .setMsg("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            r .setCode(500);
            r .setMsg("系统出现了故障");
        }

        return r ;
    }

    //编辑员工信息
    @Override
    public R updateEmp(Employee employee) {

        R r = new R();

        try {
            Integer row = sysEmployeeMapper.updateEmp(employee);
            if(row>0){
                r .setCode(200);
                r .setMsg("修改成功");
            }else{
                r .setCode(500);
                r .setMsg("修改失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            r .setCode(500);
            r .setMsg("系统出现了故障了");
        }
        return r ;
    }




    @Override
    public R initMenuByEmpId(Integer empId) {

        List<Menu> initMenu=new ArrayList<>();
        List<Menu> menus = menMapper.getinitMenuByUserId(empId);

        Iterator<Menu> iterator = menus.iterator();
        while (iterator.hasNext()){
            Menu next = iterator.next();
            if (next.getMgr()==0){
                initMenu.add(next);
                iterator.remove();
            }
        }
        getData(menus,initMenu);

        return R.ok(initMenu);





    }


    public void getData(List<Menu> menu, List<Menu> pp){

        for (int j = 0; j < pp.size(); j++) {
            Menu tree = pp.get(j);
            List<Menu> permissionTrees=new ArrayList<>();

            boolean flag=false;

            for (int i = 0; i < menu.size(); i++) {
                Menu next= menu.get(i);
                if (next.getMgr()==tree.getMenuId()){
                    flag=true;
                    permissionTrees.add(next);
                    if (ObjectUtils.isEmpty(tree.getComponentView())||"".equals(tree.getComponentView())){
                        tree.setComponentView(next.getComponentView());
                    }

                    tree.setMenuChilds(permissionTrees);
                    getData(menu,permissionTrees);
                }
            }

            if (!flag) return;

            tree.setMenuChilds(permissionTrees);
        }
    }


}
